/*
 * Copyright (c) 2009, Hamish Morgan. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the University of Sussex nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package piccat.lib;

import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Singleton class that manages the loading of iamge file resources.
 *
 * @author Hamish Morgan
 */
public class ImageLoader {

    protected final Logger log = LoggerFactory.getLogger(
            this.getClass().getName());
    private static final Dimension NULL_DIM = new Dimension(-1, -1);
    private static ImageLoader INSTANCE = new ImageLoader();
    private final Map<Key, Image> images;

    private ImageLoader() {
        images = new HashMap<Key, Image>();
    }

    public static ImageLoader getInstance() {
        return INSTANCE;
    }

    public static Image getImage(URL imageUrl) {
        final Key key = new Key(imageUrl, NULL_DIM);
        final ImageLoader il = getInstance();
        if (!il.images.containsKey(key))
            il.images.put(key, il.loadImage(key.url));
        return il.images.get(key);
    }

    public static Image getImage(URL imageUrl, Dimension size) {
        final Key key = new Key(imageUrl, size);
        final ImageLoader il = getInstance();
        if (!il.images.containsKey(key)) {
            Image im = getImage(imageUrl);
            im = il.resizeImage(im, size);
            il.images.put(key, im);
        }
        return il.images.get(key);
    }

    private Image loadImage(URL url) {
        log.info("Loading image: " + url);
        Image im = Toolkit.getDefaultToolkit().createImage(url);
        if (im == null)
            throw new RuntimeException("Failed to load image: " + url);
        return im;
    }

    private Image resizeImage(Image im, Dimension dim) {
        log.info("Scaling image size: " + dim);
        if(dim.width == 0 || dim.height == 0)
            return im;
        return im.getScaledInstance(dim.width, dim.height,
                Image.SCALE_SMOOTH);

    }

    private static class Key {

        private final URL url;
        private final Dimension dim;

        public Key(URL url, Dimension dim) {
            this.url = url;
            this.dim = dim;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null) return false;
            if (getClass() != obj.getClass()) return false;
            final Key other = (Key) obj;
            if (this.url != other.url &&
                    (this.url == null || !this.url.equals(other.url)))
                return false;
            if (this.dim != other.dim &&
                    (this.dim == null || !this.dim.equals(other.dim)))
                return false;
            return true;
        }

        @Override
        public int hashCode() {
            int hash = 5;
            hash = 23 * hash + (this.url != null ? this.url.hashCode() : 0);
            hash = 23 * hash + (this.dim != null ? this.dim.hashCode() : 0);
            return hash;
        }
    }
}
